package com.superdaxue.rxsampledemo;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Build;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.superdaxue.rxsampledemo.adapter.RvAdapter;
import com.superdaxue.rxsampledemo.bean.DataBean;
import com.superdaxue.rxsampledemo.broadcast.NetWorkBroadcastReceiver;
import com.superdaxue.rxsampledemo.configs.AppConfigs;
import com.superdaxue.rxsampledemo.presenter.ShowContentPresenter;
import com.superdaxue.rxsampledemo.utils.BaseRecyclerAdapter;
import com.superdaxue.rxsampledemo.utils.RecyclerItemDecoration;
import com.superdaxue.rxsampledemo.view.ShowContentView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements ShowContentView{
    private ShowContentPresenter presenter;
    private RvAdapter adapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private  int mLastVisibleItem;
    private int page = 1;
    private List<DataBean.ShowapiResBodyBean.NewslistBean> dataList;
    private long current ;
    private NetWorkBroadcastReceiver netWorkBroadcastReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        registerBroadcast();
        initView();
    }

    /**
     * 注册广播
     */
    private void registerBroadcast() {
        netWorkBroadcastReceiver = new NetWorkBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkBroadcastReceiver, intentFilter);
    }

    /**
     * 取消注册广播
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.cancel();
        unregisterReceiver(netWorkBroadcastReceiver);
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void initView() {
        dataList = new ArrayList<>();
        presenter = new ShowContentPresenter(MainActivity.this);

        //RecyclerView
        RecyclerView rv = (RecyclerView) findViewById(R.id.rv_main);
        GridLayoutManager manager = new GridLayoutManager(MainActivity.this,2);
        rv.setLayoutManager(manager);
        //设置间距
        RecyclerItemDecoration recyclerItemDecoration = new RecyclerItemDecoration(16);
        rv.addItemDecoration(recyclerItemDecoration);

        adapter = new RvAdapter(rv,R.layout.item_img_fragment_layout);
        rv.setAdapter(adapter);

        //RecyclerView设置上拉加载更多
        rv.setOnScrollChangeListener(new RecyclerView.OnScrollChangeListener(){
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                RecyclerView rView = (RecyclerView) v;
                int lastVisible = ((GridLayoutManager)rView.getLayoutManager()).findLastVisibleItemPosition();
                if (!presenter.getRefreshState() && rView.getAdapter().getItemCount() - 1 == lastVisible && lastVisible != mLastVisibleItem){
                    mLastVisibleItem = lastVisible;
                    presenter.getListData(++ page);
                }
            }
        });

        rv.addOnScrollListener(new RecyclerView.OnScrollListener(){

        });

        //通过AdapterRecycler设置点击监听
        adapter.setItemListener(new BaseRecyclerAdapter.OnRecyclerItemClickListener() {
            @Override
            public void onRecyclerItemClick(View view, Object data, int position) {
                DataBean.ShowapiResBodyBean.NewslistBean newslistBean = (DataBean.ShowapiResBodyBean.NewslistBean) data;
                startActivity(newslistBean.getUrl(),WebActivity.class);
            }
        });

        //设置FooterView
        setFooterView(R.layout.recyclerview_footer);
        //设置HeaderView
        setHeaderView(R.layout.recyclerview_header);
        //SwipeRefreshLayout
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.srfl_main);
        showBar();//第一次进来展示刷新圆圈

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if ( !presenter.getRefreshState() )
                       presenter.getListData(page);
            }
        });

        //请求数据 .....这里放在监听广播里了
        // presenter.getListData(page);

    }

    private void setHeaderView(int layoutId) {
        View v = LayoutInflater.from(MainActivity.this).inflate(layoutId,null);
        adapter.setHeaderView(v);
    }

    private void setFooterView(int layoutId) {
        View v = LayoutInflater.from(MainActivity.this).inflate(layoutId,null);
        adapter.setFooterView(v);
    }

    private void startActivity(String url,Class<? extends Activity>activity){
        Intent intent = new Intent(MainActivity.this,activity);
        Bundle bundle = new Bundle();
        bundle.putString(AppConfigs.BUNDLE_URL,url);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void showBar(){
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
            }
        });
    }

    /**
     * 成功拿到请求数据后的接口回调
     * @param dataBean
     */
    @Override
    public void onShow(DataBean dataBean) {
        DataBean.ShowapiResBodyBean showapiResBodyBean = dataBean.getShowapi_res_body();
        if (showapiResBodyBean != null){
            dataList.addAll(showapiResBodyBean.getNewslist());
            adapter.setDataList(dataList);
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    /**
     * 请求数据失败，提示信息
     * @param message
     */
    @Override
    public void onFailedMessage(String message) {
        swipeRefreshLayout.setRefreshing(false);
        toast(AppConfigs.DATA_FAILED+"/n"+message);
    }

    /**
     * 没有网络的时候
     */
    @Override
    public void onNoNetWork() {
          toast(AppConfigs.NO_NET);
    }

    /**
     * 断网后 Wifi又连接上
     */
    @Override
    public void onHaveWifi() {
           showBar();
           presenter.getListData(page);
    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - current > 2000){
            current = System.currentTimeMillis();
            toast(AppConfigs.AGAIN_EXIT);
        }else{
            finish();
            System.exit(0);
        }
    }

    private void toast(String string){
        Toast.makeText(MainActivity.this,string,Toast.LENGTH_LONG).show();
    }
}
